/*-
 * Copyright (c) 2009 Jonathan Anderson
 * All rights reserved.
 *
 * WARNING: THIS IS EXPERIMENTAL SECURITY SOFTWARE THAT MUST NOT BE RELIED
 * ON IN PRODUCTION SYSTEMS.  IT WILL BREAK YOUR SOFTWARE IN NEW AND
 * UNEXPECTED WAYS.
 * 
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, Inc. 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <errno.h>

#include <cstdlib>
#include <map>
#include <string>

#include "Crypto.h"

using namespace std;



Crypto& Crypto::instance() { static Crypto instance; return instance; }
Crypto::Crypto()
{
	// seed the random number generator
	srand(time(0));
	rand();

	// initialize the encryption / decryption key(s)
	char buffer[AES_BLOCK_SIZE];
	for(unsigned int i = 0; i < AES_BLOCK_SIZE; i += sizeof(int))
		*((int*) buffer + i * sizeof(int)) = rand();

	AES_set_encrypt_key((unsigned char*) buffer, 128, &encryptKey);
	AES_set_decrypt_key((unsigned char*) buffer, 128, &decryptKey);

	// initialize the MAC key
	for(unsigned int i = 0; i < AES_BLOCK_SIZE; i += sizeof(int))
		*((int*) buffer + i * sizeof(int)) = rand();

	AES_set_encrypt_key((unsigned char*) buffer, 128, &macKey);
}



struct file_struct
{
	char magic[AES_BLOCK_SIZE];
	int32_t fd;
	int32_t namelen;

	/* bytes to hold the name */
};



Crypto::Ciphertext Crypto::generateToken(int fd, QString filename)
{
	unsigned int size = sizeof(struct file_struct) + filename.length() + 1;
	size += (AES_BLOCK_SIZE - (size % AES_BLOCK_SIZE));  // pad to an AES block

	struct file_struct *f = (struct file_struct*) malloc(size);
	char *name = ((char*) f) + sizeof(struct file_struct);

	for(int i = 0; i < (AES_BLOCK_SIZE / sizeof(int)); i++)
	{
		int r = rand();
		memcpy(f->magic + i * sizeof(int), &r, sizeof(int));
	}

	f->fd = fd;
	f->namelen = filename.length();
	memcpy(name, filename.toStdString().c_str(), f->namelen);
	name[f->namelen] = '\0';

	const unsigned char *plaintext          = (unsigned char*) f;
	unsigned char *ciphertext               = new unsigned char[size];
	unsigned char *mac                      = new unsigned char[size];
	unsigned char iv[AES_BLOCK_SIZE];       bzero(iv, AES_BLOCK_SIZE);

	AES_cbc_encrypt(plaintext, ciphertext, size, &encryptKey, iv, 1);
	AES_cbc_encrypt(plaintext, mac, size, &macKey, iv, 1);

	Ciphertext result;
	result.ciphertext   = QByteArray((const char*) ciphertext, size);
	result.mac          = QByteArray((const char*) mac + size - AES_BLOCK_SIZE,
	                                 AES_BLOCK_SIZE);

	delete [] ciphertext;
	delete [] mac;

	return result;

/*
	const unsigned int TOKEN_SIZE = 2 * (size + AES_BLOCK_SIZE) + 2;

	char *token = new char[TOKEN_SIZE + 1];
	bzero(token, TOKEN_SIZE + 1);

	char *head = token;
	for(unsigned int i = 0; i < size; i++, head += 2)
		sprintf(head, "%02x", 0xff & ciphertext[i]);

	*(head++) = '/';

	for(unsigned int i = 0; i < AES_BLOCK_SIZE; i++, head += 2)
		sprintf(head, "%02x", 0xff & mac[size - AES_BLOCK_SIZE + i]);

	*head = '\0';

	string t(token);

	delete [] ciphertext;
	delete [] token;

	return t;*/
}

